<?php

namespace app\common\traits;

use yiqiniu\extend\facade\Arrays;

trait SystemMenuTrait
{


    /**
     * 根据用户登录后的路由菜单
     * @param array $menus
     * @param bool $node
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMenuAuth(array $menus, bool $node = false): array
    {
        $db = $this->db()->where('is_show', 1)
            ->order('order_id desc,id asc')->field('id,title,pid,front,page_action,icon,child,depth');
        if (!empty($menus)) {
            $db = $db->where(function ($query) use ($menus, $node) {
                $query->whereIn($node ? 'page_action' : 'id', $menus)->whereOr('pid', 0);
            });
        }
        $list = $db->select();
        //        $result = [];
//        foreach ($list as $item) {
//            if (empty($item['children'])) {
//                continue;
//            }
//            $front = $item['front'];
//            $front['children'] = array_column($item['children'], 'front');
//            $result[] = $front;
//        }
        return Arrays::toTree($list, 'id', 'pid');
    }

    /**
     * 保存数据
     * @param $data
     * @throws \think\Exception
     */
    public function addEdit($data): void
    {
        $this->TreeAddEdit($data);
    }

    /**
     * 删除菜单节点
     * @param int $id 要删除的菜单ID
     * @return int
     * @throws \think\db\exception\DbException
     * @throws \yiqiniu\extend\exception\ApiException
     */
    public function del($id)
    {
        if ($this->db()->removeOption()->where("pid", $id)->count() > 0) {
            api_exception(API_ERROR, "该菜单下还有下级菜单,请先维护下级菜单");
        }
        return $this->db()->removeOption()->where(["id" => $id])->delete();

    }
}
